/*
 * This file is part of Catfish.
 * Copyright (C) 2010 Namazu Studios LLC
 * 
 * Catfish is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version.
 * 
 * Catfish is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with Catfish.  If not, please visit:
 *  
 * http://www.gnu.org/licenses/
 *  
 */
package com.namazustudios.catfish.converter;

import java.lang.reflect.Type;

import com.google.inject.Singleton;
import com.namazustudios.catfish.CatfishException;
import com.namazustudios.catfish.annotation.Name;

/**
 * Converts enumerations to Strings such that they can be stored in the
 * datastore.
 * 
 * @author patrick
 * 
 */
@Singleton
@Name(name="enum")
public class EnumConverter implements Converter<String, Enum<?>> {

    @Override
    public String store(Enum<?> obj) {
        return obj == null ? null : obj.toString();
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Enum<?> load(Type type, Enum<?> existing, String obj) {

        if (!Enum.class.isAssignableFrom((Class<?>)type)) {
            throw new CatfishException(type + "is not an enum type!");
        }

        return obj == null ? null : Enum.valueOf((Class<Enum>) type, obj);
    }

}
